package memo.action;

import java.util.Date;

import memo.dao.ListMemoDAO;
import memo.pojo.ListMemo;
import model.pojo.Employee;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import approve.action.LoginActivity;
import approve.action.LogoutActivity;
import approve.action.MainEApproval;
import approve.action.R;

public class Memo_oneview extends Activity {
	TextView logout,username,home,welcome;

	ListMemo privateMemo = new ListMemo();

	TextView lbTitle,lbContent,valueTitle,valueContent,textPrivateMemo;

	Button btEdit,btDelete,btBack;
	Button buttonBack;

	ListMemoDAO listMemoDAO = new ListMemoDAO();

	String vTitle,vContent;
	Bundle extras;
	
	private final Handler uiHandler=new Handler();
	private boolean isUpdateRequired=false;
	TextView tvwaiting;
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;
	int flagviewpopup=0;
	
	public AlertDialog getAlertwaiting() {
		return alertwaiting;
	}

	public void setAlertwaiting(AlertDialog alertwaiting) {
		this.alertwaiting = alertwaiting;
	}

	public boolean isUpdateRequired() {
		return isUpdateRequired;
	}

	public void setUpdateRequired(boolean isUpdateRequired) {
		this.isUpdateRequired = isUpdateRequired;
	}

	public Handler getUiHandler() {
		return uiHandler;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try{
			initall();
		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
	public void initall(){
		
		setContentView(R.layout.memo_oneview);

		loadExtra();

		logout=(TextView)findViewById(R.id.logout);
		username=(TextView)findViewById(R.id.username);
		logout.setText(LoginActivity.lang.getString("Logout"));

		logout.setOnClickListener(listenerLogout);
		username.setText(LoginActivity.emp.getUserName());

		welcome = (TextView)findViewById(R.id.welcome);
		welcome.setText(LoginActivity.lang.getString("ac_Welcome"));

		buttonBack = (Button)findViewById(R.id.buttonBack);

		initAttribute();

		valueTitle.setText(privateMemo.getTitle().toString());
		valueContent.setText(privateMemo.getContent());

		btEdit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				btEdit.setBackgroundResource(R.drawable.bt_general_pressed);
				if(flagviewpopup==0){
					flagviewpopup=1;
					processEditPrivateMemo();
				}
			}
		});

		btDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(flagviewpopup==0){
					flagviewpopup=1;
					processDeletePrivateMemo();
				}
				
			}
		});


		buttonBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				buttonBack.setBackgroundResource(R.drawable.bg_back_pressed);
				Intent intent = new Intent(Memo_oneview.this,Memo_listview.class);
				intent.putExtras(extras);
				startActivity(intent);
				finish();
			}
		});

		RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.relativeTitle);
		Resources res = getResources();
		final BitmapDrawable background = (BitmapDrawable) res.getDrawable(R.drawable.bg_menu_item);
		background.setTileModeX(Shader.TileMode.REPEAT);
		background.setTileModeY(Shader.TileMode.REPEAT);
		background.setDither(true);
		relativeLayout.setBackgroundDrawable(background);
		
		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		tvwaiting.setText(LoginActivity.lang.getString("waiting")+"...");

		builderwaiting = new AlertDialog.Builder(Memo_oneview.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();
	}

	public void initAttribute(){
		lbTitle = (TextView)findViewById(R.id.textlbTitleMemo);
		lbTitle.setText(LoginActivity.lang.getString("title")+": ");
		lbTitle.setTextColor(Color.YELLOW);
		lbContent = (TextView)findViewById(R.id.textlbContentMemo);
		lbContent.setText(LoginActivity.lang.getString("content") +": ");
		lbContent.setTextColor(Color.YELLOW);

		textPrivateMemo = (TextView)findViewById(R.id.textPrivateMemo);
		textPrivateMemo.setText(LoginActivity.lang.getString("privateMemo"));

		valueTitle =(TextView)findViewById(R.id.textValueTitleMemo);
		valueContent = (TextView)findViewById(R.id.textValueComtentMemo);

		btEdit = (Button)findViewById(R.id.buttonDetailEdit);
		btEdit.setText(LoginActivity.lang.getString("Edit"));
		btDelete = (Button)findViewById(R.id.buttonDetailDelete);
		btDelete.setText(LoginActivity.lang.getString("Delete"));
	}

	public void loadExtra() {
		extras = getIntent().getExtras();
		if (extras != null) {
			privateMemo = (ListMemo)extras.get("itemmemo");
		}
	}
	
	private OnClickListener listenerLogout=new OnClickListener() {

		public void onClick(View v) {
			logout.setTextColor(Color.parseColor("#1188ff"));
			LoginActivity.flagruntimer=true;
			LoginActivity.soluong=0;
			LoginActivity.emp=new Employee();
			MainEApproval.mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
			MainEApproval.timer.cancel();
			Intent i=new Intent(Memo_oneview.this, LogoutActivity.class);
			startActivity(i);
			finish();
		}
	};

	private void processDeletePrivateMemo(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(LoginActivity.lang.getString("Delete"));
		builder.setMessage(LoginActivity.lang.getString("areyousure")+" ?");

		builder.setPositiveButton(LoginActivity.lang.getString("ok"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
//				btDelete.setBackgroundResource(R.drawable.bt_general_normal);
				alertwaiting.show();
				try{
					new Thread(){
						public void run() {
							listMemoDAO.deleteMemo(privateMemo.getId(), LoginActivity.database);
							uiHandler.post( new Runnable(){
								@Override
								public void run() {
									if(isUpdateRequired){
									}else{
										Intent intent = new Intent(Memo_oneview.this, Memo_listview.class);
										startActivity(intent);
										finish();
										alertwaiting.cancel();
									}
								}
							} );
						}
					}.start();
				}catch (Exception e) {}
				
				flagviewpopup=0;
			}
		});

		builder.setNegativeButton(LoginActivity.lang.getString("cancel"), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				flagviewpopup=0;
			}
		});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	private void processEditPrivateMemo(){
		Rect displayRectangle = new Rect();
		Window window = Memo_oneview.this.getWindow();
		window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);


		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		final View textEntryView = inflater.inflate(R.layout.memo_addnew, null);

		final TextView lbtitleMemo = (TextView)textEntryView.findViewById(R.id.memo_add_tvtitle);
		final TextView lbcontentMemo = (TextView)textEntryView.findViewById(R.id.memo_add_tvcontent);
		lbtitleMemo.setText(LoginActivity.lang.getString("title"));
		lbcontentMemo.setText(LoginActivity.lang.getString("content"));

		final EditText edTitleMemo = (EditText)textEntryView.findViewById(R.id.memo_add_ettitle);
		edTitleMemo.setText(privateMemo.getTitle());
		final EditText edContentMemo = (EditText)textEntryView.findViewById(R.id.memo_add_etcontent);
		
		textEntryView.setMinimumWidth((int)(displayRectangle.width() * 1f));
		textEntryView.setMinimumHeight((int)(displayRectangle.height() * 1f));
		
		edContentMemo.setText(privateMemo.getContent());
		
		final Button buttonSave = (Button)textEntryView.findViewById(R.id.bttSaveMemo);
		buttonSave.setText(LoginActivity.lang.getString("save"));
		final Button buttonReset = (Button)textEntryView.findViewById(R.id.bttResetMemo);
		buttonReset.setText(LoginActivity.lang.getString("ac_ma_Reset"));
		final Button buttonClose = (Button)textEntryView.findViewById(R.id.bttCloseMemo);
		buttonClose.setText(LoginActivity.lang.getString("Close"));

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(LoginActivity.lang.getString("editprivatememo"));
		builder.setView(textEntryView);
		builder.setCancelable(false);
		final AlertDialog alert = builder.create();
		alert.show();

		buttonReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				edTitleMemo.setText("");
				edContentMemo.setText("");
			}
		});

		buttonClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				btEdit.setBackgroundResource(R.drawable.bt_general_normal);
				flagviewpopup=0;
				alert.cancel();
			}
		});

		buttonSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				btEdit.setBackgroundResource(R.drawable.bt_general_normal);
				if(!edTitleMemo.getText().toString().equals("")){
					
					alert.cancel();
					alertwaiting.show();
					try{
						new Thread(){
							public void run() {
								vTitle="";
								vContent="";
								privateMemo.setTitle(edTitleMemo.getText().toString());
								privateMemo.setContent(edContentMemo.getText().toString());
								privateMemo.setCreatedDate(new Date());
								privateMemo.setStatus(1);
								final boolean kq=listMemoDAO.updateMemo(privateMemo, LoginActivity.database);							
								
								uiHandler.post( new Runnable(){
									@Override
									public void run() {
										if(isUpdateRequired){
										}else{
											if(kq==true){
												valueTitle.setText(privateMemo.getTitle());
												valueContent.setText(privateMemo.getContent());
											}
											alertwaiting.cancel();
										}
									}
								} );
							}
						}.start();
					}catch (Exception e) {}
					
					flagviewpopup=0;
					
				}else{
					vTitle = edTitleMemo.getText().toString();
					vContent = edContentMemo.getText().toString();

					Toast.makeText(getApplicationContext(), LoginActivity.lang.getString("isempty"),Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	public void onBackPressed() {
		
		Memo_oneview.this.getAlertwaiting().show();
		try{
			new Thread(){
				public void run() {
					Intent intent = new Intent(Memo_oneview.this,Memo_listview.class);
					startActivity(intent);
					finish();
					Memo_oneview.this.getUiHandler().post( new Runnable(){
						@Override
						public void run() {
							if(Memo_oneview.this.isUpdateRequired()){
							}else{
								Memo_oneview.this.getAlertwaiting().cancel();
							}
						}
					} );
				}
			}.start();
		}catch (Exception e) {}
	};

	// Main menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(getApplicationContext());
		if(LoginActivity.typeLang.equals("EN")){
			inflater.inflate(R.menu.option_main_menu, menu);
		}else if(LoginActivity.typeLang.equals("VN")){
			inflater.inflate(R.menu.option_main_menuvn, menu);
		}else{
			inflater.inflate(R.menu.option_main_menukr, menu);
		}

		setMenuBackground();
		return true;
	}
	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  


			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.drawable.border_footer);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(LoginActivity.typeLang.equals("VN")){
			switch (item.getItemId()) {
			case R.id.menu_eappvn:
				processMenuEApproval();
				return true;
			case R.id.menu_primemovn:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else if(LoginActivity.typeLang.equals("KR")){
			switch (item.getItemId()) {
			case R.id.menu_eappkr:
				processMenuEApproval();
				return true;
			case R.id.menu_primemokr:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else{
			switch (item.getItemId()) {
			case R.id.menu_eapp:
				processMenuEApproval();
				return true;
			case R.id.menu_primemo:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	}

	public void processMenuEApproval(){
		Intent intent = new Intent(Memo_oneview.this,MainEApproval.class);
		startActivity(intent);
		finish();
	}

	public void processMenuPrivateMemo(){
		Intent intent = new Intent(Memo_oneview.this,Memo_listview.class);
		startActivity(intent);
		finish();
	}
}